package dk.jagtogjaeger.domain;

import java.util.Collection;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DBFacade {

	private static final String TAG = DBFacade.class.getSimpleName();
	private static DBFacade instance = null;
	private static DBHelper helper = null;

	protected DBFacade() {
		Log.d(TAG, " DBFacade Instance created");
	}

	public boolean createJournal(HuntJournal journal) {
		HuntJournalDBAdapter jMapper = new HuntJournalDBAdapter();
		SQLiteDatabase db = helper.getWritableDatabase();
		open();
		boolean res = jMapper.createJournal(db, journal);
		close(db);
		return res;
	}

	public boolean updateJournal(HuntJournal journal) {
		HuntJournalDBAdapter jMapper = new HuntJournalDBAdapter();
		SQLiteDatabase db = helper.getWritableDatabase();
		open();
		boolean res = jMapper.updateJournal(db, journal);
		close(db);
		return res;
	}

	public boolean deleterJournal(HuntJournal journal) {
		HuntJournalDBAdapter jMapper = new HuntJournalDBAdapter();
		SQLiteDatabase db = helper.getReadableDatabase();
		open();
		boolean res = jMapper.deleteJournal(db, journal);
		close(db);
		return res;
	}

	public Collection<HuntJournal> getJournals() {
		HuntJournalDBAdapter jMapper = new HuntJournalDBAdapter();
		SQLiteDatabase db = helper.getReadableDatabase();
		open();
		Collection<HuntJournal> res = jMapper.fetchAllJournals(db);
		close(db);
		return res;

	}

	public String[] getSpeciesArray() {
		HuntJournalDBAdapter jMapper = new HuntJournalDBAdapter();
		SQLiteDatabase db = helper.getReadableDatabase();
		open();
		String[] res = jMapper.getAllSpecies(db);
		close(db);

		return res;

	}

	public Collection<TrackerDog> fetchAllTrackerDogs() {
		TrackerDogDBAdapter trackerDogDBAdapter = new TrackerDogDBAdapter();
		Collection<TrackerDog> res;
		SQLiteDatabase db = helper.getReadableDatabase();
		open();
		res = trackerDogDBAdapter.fetchAllTrackerDogs(db);
		close(db);
		return res;
	}

	public static DBFacade getInstance(Context context) {
		if (instance == null) {
			instance = new DBFacade();
		}
		helper = new DBHelper(context);

		return instance;
	}

	private SQLiteDatabase open() {
		return helper.getWritableDatabase();
	}

	private void close(SQLiteDatabase db) {
		db.close();
	}

}
